// pages/competition/index.js
const system = require('../../utils/system.js');
const { competitionApi } = require('../../utils/api.js');

// 获取应用实例
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    competitions: [],
    loading: true,
    statusBarHeight: 0,
    navBarHeight: 44,
    bottomSafeHeight: 0,
    showBackBtn: false,
    userId: null, // 默认为null，表示未登录
    username: '', // 默认为空
    positionTypes: {}, // 存储每个竞赛的职位类型，格式为 {competitionId: positionType}
    isLoggedIn: false, // 是否已登录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取当前页面栈
    const pages = getCurrentPages();
    // 设置状态栏高度等数据
    this.setData({
      statusBarHeight: system.statusBarHeight,
      navBarHeight: 44,
      bottomSafeHeight: system.bottomSafeHeight,
      showBackBtn: pages.length > 1 // 如果页面栈大于1，显示返回按钮
    });
    
    // 检查登录状态
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus() {
    // 获取用户信息
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    if (token && userInfo) {
      this.setData({
        userId: userInfo.id,
        username: userInfo.username || '',
        isLoggedIn: true
      });
      
      // 加载模考大赛数据
      this.loadCompetitions();
    } else {
      this.setData({
        userId: null,
        username: '',
        isLoggedIn: false,
        loading: false
      });
      
      // 提示用户登录
      wx.showModal({
        title: '提示',
        content: '请先登录后查看模考大赛',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/index'
            });
          }
        }
      });
    }
  },

  // 加载模考大赛数据
  loadCompetitions() {
    // 如果未登录，不加载数据
    if (!this.data.isLoggedIn || !this.data.userId) {
      this.setData({ loading: false });
      return;
    }
    
    this.setData({ loading: true });
    
    competitionApi.getAllCompetitions(this.data.userId)
      .then(competitions => {
        // 格式化参与人数
        const formattedCompetitions = competitions.map(comp => {
          return {
            ...comp,
            participantsFormatted: (comp.currentParticipants || 0).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','),
            // 将考试时间格式化为前端显示格式
            timeInfo: [
              `行测: ${comp.examTime.substring(0, 16).replace('T', ' ')} - ${this.calculateEndTime(comp.examTime, comp.duration)}`
            ]
          };
        });
        
        this.setData({
          competitions: formattedCompetitions,
          loading: false
        });
      })
      .catch(err => {
        console.error('获取模考大赛失败:', err);
        wx.showToast({
          title: '获取模考大赛失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },

  // 计算考试结束时间
  calculateEndTime(startTime, durationMinutes) {
    const startDate = new Date(startTime);
    const endDate = new Date(startDate.getTime() + durationMinutes * 60000);
    return `${endDate.getHours().toString().padStart(2, '0')}:${endDate.getMinutes().toString().padStart(2, '0')}`;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时检查登录状态并刷新数据
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadCompetitions();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 返回上一页
   */
  navigateBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 查看考试详情
  viewExamDetails: function(e) {
    const id = e.currentTarget.dataset.id;
    const competition = this.data.competitions.find(item => item.id === id);
    
    if (!competition) return;
    
    wx.showModal({
      title: '考试说明',
      content: competition.description || '本场模拟考试旨在为考生提供真实考场环境体验，题目难度与真题相当。请在规定时间内认真作答，系统将自动判分并生成成绩报告。',
      showCancel: false,
      confirmText: '我知道了'
    });
  },

  // 开启考试提醒
  startExam: function(e) {
    // 检查是否已登录
    if (!this.data.isLoggedIn || !this.data.userId) {
      this.showLoginTip();
      return;
    }
    
    const id = parseInt(e.currentTarget.dataset.id);
    
    // 先显示加载状态
    wx.showLoading({
      title: '设置中...',
      mask: true
    });
    
    competitionApi.setRemindStatus(this.data.userId, id, true)
      .then(result => {
        wx.hideLoading();
        
        // 更新本地数据
        const competitions = [...this.data.competitions];
        const index = competitions.findIndex(item => item.id === id);
        
        if (index !== -1) {
          competitions[index].isReminded = true;
          this.setData({ competitions });
        }
        
        wx.showToast({
          title: '考试提醒已开启',
          icon: 'success',
          duration: 2000
        });
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: err.message || '设置失败',
          icon: 'none'
        });
      });
  },

  // 立即报名
  register: function(e) {
    // 检查是否已登录
    if (!this.data.isLoggedIn || !this.data.userId) {
      this.showLoginTip();
      return;
    }
    
    const id = parseInt(e.currentTarget.dataset.id);
    
    // 检查是否选择了职位
    if (!this.data.positionTypes[id]) {
      this.addPosition(id, () => this.doRegister(id));
      return;
    }
    
    this.doRegister(id);
  },
  
  // 执行报名操作
  doRegister: function(id) {
    // 检查是否已登录
    if (!this.data.isLoggedIn || !this.data.userId) {
      this.showLoginTip();
      return;
    }
    
    // 检查是否选择了职位
    if (!this.data.positionTypes[id]) {
      wx.showToast({
        title: '请先选择职位类型',
        icon: 'none'
      });
      return;
    }
    
    // 先显示加载状态
    wx.showLoading({
      title: '报名中...',
      mask: true
    });
    
    console.log(`为竞赛 ${id} 报名，选择的职位类型:`, this.data.positionTypes[id]);
    
    competitionApi.register(
      this.data.userId, 
      this.data.username, 
      id, 
      this.data.positionTypes[id]
    )
      .then(result => {
        wx.hideLoading();
        
        // 更新本地数据
        const competitions = [...this.data.competitions];
        const index = competitions.findIndex(item => item.id === id);
        
        if (index !== -1) {
          const newParticipants = competitions[index].currentParticipants + 1;
          competitions[index].currentParticipants = newParticipants;
          competitions[index].participantsFormatted = newParticipants.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
          competitions[index].isRegistered = true;
          this.setData({ competitions });
        }
        
        wx.showToast({
          title: '报名成功',
          icon: 'success',
          duration: 2000
        });
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: err.message || '报名失败',
          icon: 'none'
        });
      });
  },
  
  // 取消报名
  cancelRegistration: function(e) {
    // 检查是否已登录
    if (!this.data.isLoggedIn || !this.data.userId) {
      this.showLoginTip();
      return;
    }
    
    const id = parseInt(e.currentTarget.dataset.id);
    
    wx.showModal({
      title: '取消报名',
      content: '确定要取消报名吗？',
      success: (res) => {
        if (res.confirm) {
          // 先显示加载状态
          wx.showLoading({
            title: '取消中...',
            mask: true
          });
          
          competitionApi.cancelRegistration(this.data.userId, id)
            .then(result => {
              wx.hideLoading();
              
              // 更新本地数据
              const competitions = [...this.data.competitions];
              const index = competitions.findIndex(item => item.id === id);
              
              if (index !== -1) {
                const newParticipants = competitions[index].currentParticipants - 1;
                competitions[index].currentParticipants = newParticipants > 0 ? newParticipants : 0;
                competitions[index].participantsFormatted = competitions[index].currentParticipants.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                competitions[index].isRegistered = false;
                competitions[index].isReminded = false;
                this.setData({ competitions });
                
                // 清除该竞赛的职位类型
                const positionTypes = {...this.data.positionTypes};
                delete positionTypes[id];
                this.setData({ positionTypes });
              }
              
              wx.showToast({
                title: '已取消报名',
                icon: 'success',
                duration: 2000
              });
            })
            .catch(err => {
              wx.hideLoading();
              wx.showToast({
                title: err.message || '取消失败',
                icon: 'none'
              });
            });
        }
      }
    });
  },
  
  // 显示登录提示
  showLoginTip: function() {
    wx.showModal({
      title: '提示',
      content: '请先登录后操作',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/index'
          });
        }
      }
    });
  },

  // 添加职位信息
  addPosition: function(e) {
    // 如果是从事件中调用，获取竞赛ID
    let id;
    if (e && e.currentTarget && e.currentTarget.dataset) {
      id = parseInt(e.currentTarget.dataset.id);
    } else if (typeof e === 'number') {
      // 如果直接传入ID
      id = e;
    } else if (typeof e === 'function') {
      // 如果是回调函数，使用第二个参数作为ID
      const callback = e;
      id = arguments[1];
      e = callback;
    }
    
    // 如果没有ID，不执行
    if (!id) {
      console.error('添加职位信息失败: 未提供竞赛ID');
      return;
    }
    
    // 获取回调函数
    let callback;
    if (typeof e === 'function') {
      callback = e;
    } else if (arguments.length > 1 && typeof arguments[1] === 'function') {
      callback = arguments[1];
    }
    
    console.log('为竞赛ID添加职位:', id);
    
    wx.showActionSheet({
      itemList: ['省考-行政执法类', '省考-综合管理类', '国考-行政执法类', '国考-综合管理类', '教师资格-小学', '教师资格-中学'],
      success: (res) => {
        if (!res.cancel) {
          const positions = ['省考-行政执法类', '省考-综合管理类', '国考-行政执法类', '国考-综合管理类', '教师资格-小学', '教师资格-中学'];
          const selectedPosition = positions[res.tapIndex];
          
          // 更新指定竞赛的职位类型
          const positionTypes = {...this.data.positionTypes};
          positionTypes[id] = selectedPosition;
          
          this.setData({ positionTypes }, () => {
            console.log('已选择职位类型:', this.data.positionTypes[id], '竞赛ID:', id);
            
            wx.showToast({
              title: '已选择职位',
              icon: 'success'
            });
            
            if (callback && typeof callback === 'function') {
              callback();
            }
          });
        }
      },
      fail: (err) => {
        console.error('选择职位失败:', err);
        wx.showToast({
          title: '请选择职位类型',
          icon: 'none'
        });
      }
    });
  }
})